import Koa from 'koa'
import KoaBody from 'koa-body'
import cors from 'koa2-cors'

import Router from 'koa-router'
import adminRoutes from './router/admin.route'
import userRoutes from './router/user.route'
import fileRoutes from './router/file.route'
import contentRoutes from './router/content.route'
import postRoutes from './router/post.route'
import notificationRoutes from './router/notification.route'

import session from 'koa-generic-session'
import redisStore from 'koa-redis'

import {Context, Next} from 'TYPE'
import config from './config/config.dev'

import {postDB} from './db/sqltable/post.db'
import {userDB} from './db/sqltable/user.db'
import {subareaDB} from './db/sqltable/subarea.db'
import {notificationDB} from './db/sqltable/notification.db'

const app = new Koa()

// error handler
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        // ctx.status = err.status || err.code;
        console.error(err);
        ctx.body = {
            code: -1,
            message: "服务器错误！！",
        };
    }
})
let {CORS_ORIGIN, USE_HTTPS} = config
// https://npm.io/package/koa2-cors
app.use(cors({
    origin: function (ctx) {
        return CORS_ORIGIN;
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'OPTIONS', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

app.keys = ["weif*)#8;^0jkl2bv=+ej"]
let cookieConfig = {
    path: "/", // cookie 所在的目录
    httpOnly: true, // js脚本将无法读取到 cookie 信息
    maxAge: 24 * 60 * 60 * 1000, // cookie 过期时间
    // sameSite: 'none',
    // secure: true
} as any

if (USE_HTTPS && USE_HTTPS != '0') {
    cookieConfig.sameSite = 'none' //samesite跨域
    cookieConfig.secure = true
}
app.use(session({
    // 配置 cookie
    cookie: cookieConfig,
    // 配置 redis
    store: redisStore({
        all: "127.0.0.1:6379",
    } as any) as any,
})
);

let {UPLOAD_PATH} = config
app.use(KoaBody({
    multipart: true,
    formidable: {
        // 上传存放的路劲
        uploadDir: UPLOAD_PATH,
        // 保持后缀名\
        keepExtensions: true,
        // 文件大小
        maxFileSize: 200 * 1024 * 1024,
        onFileBegin: (name, file) => {
            // 获取后缀, 如: .js  .txt
            // const reg = /\.[A-Za-z]+$/g
            // const ext = file.originalFilename.match(reg)[0]
            //修改上传文件名
            // file.newFilename = Date.now() + ext;
        },
    }
}))
app.use(async (ctx, next) => {
    Object.keys(ctx.query).map(k => {
        if (k.endsWith('[]')) {
            if (!Array.isArray(ctx.query[k])) {
                ctx.query[k] = [ctx.query[k]] as string[]
            }
        }
    })
    await next();
})

const router = new Router()

app.use(router.routes())
app.use(userRoutes)
app.use(adminRoutes)
app.use(fileRoutes)
app.use(contentRoutes)
app.use(postRoutes)
app.use(notificationRoutes)

app.use(async (ctx: Context, next: Next) => {// 将ctx.msg,return,code返回
    ctx.body = ctx.body || {}
    ctx.body.code = ctx.cd
    if (ctx.msg)
        ctx.body.message = ctx.msg
    if (ctx.return)
        ctx.body.return = ctx.return
    // console.log(ctx.body);
    await next()
})

import https from 'https'
import sslify from 'koa-sslify'
import fs from 'fs'
Promise.all([
    postDB.initIndex(),
    subareaDB.initIndex(),
    userDB.initIndex(),
    notificationDB.initIndex()
]).then(() => {
    let {APP_PORT} = config

    if (USE_HTTPS && USE_HTTPS != '0') {
        let {SSL_KEY, SSL_CRT} = config
        app.use(sslify())
        https.createServer({
            key: fs.readFileSync(SSL_KEY),
            cert: fs.readFileSync(SSL_CRT),
        }, app.callback()).listen(APP_PORT, () => {
            console.log(`https://your-host:${APP_PORT}`);
        })
    } else {
        app.listen(APP_PORT, () => {
            console.log(`http://your-host:${APP_PORT}`);
        })
    }
})


import readline from 'readline'
import knex from './db/sql'
import {cache} from './db/cache'
import {sleep} from 'sleep'
// let loadData = false
// if (loadData) {
//     let rl = readline.createInterface({
//         input: fs.createReadStream("/home/pde/code/data/wiki/wiki.txt", 'utf8')
//     })
//     let i = 0
//     let postids = []
//     let authors = [10022, 10023, 10029, 10030]
//     try {
//         cache.ft.dropIndex('idx:posts')
//         cache.ft.dropIndex('idx:comments')
//     } catch {}
//     let ranElm = (arr: any[]) => {return arr[Math.floor(Math.random() * arr.length)]}
//     rl.on('line', async line => {
//         // if(i < 339000) return
//         if (i >= 1300001) return
//         if (line.startsWith('=') || line.startsWith('*') || line.length <= 5) return
//         if (i > 999999999) {
//             const str = line.substring(0, 1000)
//             if (!(i % 3) && postids.length) {
//                 await knex('comments').insert({pid: ranElm(postids), content: str, author: ranElm(authors), status: 0}).then(res => {
//                 })
//             } else {
//                 await knex('posts').insert({content: str, subarea: 10001, author: ranElm(authors), status: 0}).then(res => {
//                     if (res.length) {
//                         postids.push(res[0])
//                     }
//                 })
//             }
//             if (i % 100 == 0) {
//                 console.clear()
//                 console.log(`已插入数据：${i}`);
//                 postids = []
//             }
//         }
//         i++
//     })
// }
